#!/usr/bin/python
# coding:utf-8
# import MySQLdb
import constant.constant_value as constant
import mysql.connector
import entry.config_bean as configBean

class Config_DB:
#     db = None
    cnn = None
    cursor = None
    def __init__(self):
        config={'host':constant.db_ip,#默认127.0.0.1
                'user':constant.db_username,
                'password':constant.db_password,
                'port':constant.db_port ,#默认即为3306
                'database':constant.db_database_name,
                'charset':'utf8'#默认即为utf8
        }
        try:
            self.cnn=mysql.connector.connect(**config)
            self.cursor=self.cnn.cursor()
        except mysql.connector.Error as e:
            print('connect fails!{}'.format(e))
        
    def getCursor(self):
        self.__init__()
        return self.cursor;
    
    #关闭连接
    def closeConn(self):
        # 关闭数据库连接
        self.cnn.close()
    #关闭光标
    def closeCursor(self):
        self.cursor.close()
    
    def testDatabase(self):
        cursor = self.getCursor()
        # 使用execute方法执行SQL语句
        cursor.execute("SELECT VERSION()")
        # 使用 fetchone() 方法获取一条数据。
        data = cursor.fetchone()
        print "Database version : %s " % data
    
    #对主表的查询操作
    def get_configs(self):
        sql = "select * from " + constant.db_config_user
        config_list = []
        try:
            # 执行sql语句      # 提交到数据库执行
            cur =self.getCursor()
            cur.execute(constant.db_use_table_name)
            cur.execute(sql)
            for row in cur.fetchall():
                config = configBean.configBean(row[0],row[1],row[2],row[3],row[4],row[5])
                config_list.append(config)
            cur = None;
            self.closeCursor()
            self.closeConn()
        except Exception as err:
            print u"查询失败了" + str(err);
        return config_list;
    
    #对主表的查询操作
    def update_configs(self,configBean):
        sql = "update "+constant.db_config_user+" set total_count = "+str(configBean.total_count)+",status_wait = "+str(configBean.status_wait)+",status_success = "+str(configBean.status_success)+" where id ='"+str(configBean.cid)+"'"
        tag = False
        try:
            cur =self.getCursor()
            cur.execute(constant.db_use_table_name)
            cur.execute(sql)
            self.cnn.commit()
            self.closeCursor()
            self.closeConn()
            tag = True
            return tag
        except Exception as err:
            # Rollback in case there is any errorr 
            print(err);
            self.closeCursor()
            self.closeConn()
            tag = False
            return tag

if __name__ == "__main__":
    db = Config_DB()
    print db.get_configs()